package me.tonywang.hellospring;

import me.tonywang.quartz.QuartzUtils;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;

import java.text.ParseException;


// @see CronTriggerFactoryBean
// @see JobDetailFactoryBean
// @see SchedulerCluserFactoryBean
//
@Configuration
@ComponentScan
public class Application {

    @Bean
    MessageService mockMessageService() {
        return () -> "Hello World!";
    }

    /**
     * SchedulerFactoryBean的代码替换
     *
     * @param args
     * @throws SchedulerException
     * @throws NoSuchMethodException
     * @throws ClassNotFoundException
     * @throws ParseException
     */
    public static void main(String[] args) throws SchedulerException, NoSuchMethodException, ClassNotFoundException, ParseException {
        ApplicationContext context =
                new AnnotationConfigApplicationContext(Application.class);
//        MessagePrinter printer = context.getBean(MessagePrinter.class);
//        printer.printMessage();

//        ArgumentConvertingMethodInvoker methodInvoker = new ArgumentConvertingMethodInvoker();
//        methodInvoker.setTargetObject(printer);
//        methodInvoker.setTargetMethod("printMessage");
//        methodInvoker.prepare();


        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        //STEP1
        MethodInvokingJobDetailFactoryBean factoryBean = new MethodInvokingJobDetailFactoryBean();
        factoryBean.setBeanFactory(context);
        factoryBean.setTargetBeanName("messagePrinter");
        factoryBean.setTargetMethod("printMessage");
        factoryBean.afterPropertiesSet();
        JobDetail job = factoryBean.getObject();

        //STEP2
        String cronExpression = "0/1 * * * * ?";
        CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
        // 1.....
        cronTriggerFactoryBean.setJobDetail(job);
        cronTriggerFactoryBean.setCronExpression(cronExpression);
        cronTriggerFactoryBean.setName("myTrigger");
        cronTriggerFactoryBean.setGroup("myTriggerGroup");
        cronTriggerFactoryBean.afterPropertiesSet();
        Trigger trigger = cronTriggerFactoryBean.getObject();

        //STEP3
//        scheduler.scheduleJob(job, trigger);

        QuartzUtils.addTriggerToScheduler(scheduler,trigger);
        QuartzUtils.start(scheduler);
//        scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(""))
    }

}
